package com.swang.pms.web.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.swang.pms.common.util.LoggerUtil;
import com.swang.pms.model.annotation.PltLog;
import com.swang.pms.model.entity.CheckPic;
import com.swang.pms.model.vo.ResultMessage;

/**
 * @ClassName: CommonServiceController
 * @Description: 通用服务controller
 * @author 王泽
 * @date 2017年3月16日 下午9:45:51
 */
@Controller
@RequestMapping("/common")
public class CommonServiceController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(CommonServiceController.class);

    @PltLog(log = "通用图片尺寸校验")
    @RequestMapping(value = "/checkPic")
    private @ResponseBody ResultMessage CheckPic(CheckPic checkPic, MultipartHttpServletRequest multipartRequest) {
        ResultMessage resultMessage = new ResultMessage(true, "图片校验成功！");
        try {
            List<CheckPic> checkPicList = new ArrayList<CheckPic>();
            if (StringUtils.isNotBlank(checkPic.getCheckPicStr())) {
                checkPicList = JSON.parseArray(checkPic.getCheckPicStr(), CheckPic.class);
            }
            checkPic.setCheckPicList(checkPicList);
            for (Iterator<String> it = multipartRequest.getFileNames(); it.hasNext();) {
                String name = it.next();
                MultipartFile imgFile = multipartRequest.getFile(name);
                if (imgFile.getSize() > 0) {
                    if ((float) imgFile.getSize() / (200 * 1024) > 1) {
                        resultMessage.setCode("MAX_SIZE_ERROR");
                        resultMessage.change(false, "上传图片大小超过200kb，是否继续上传？");
                        return resultMessage;
                    }
                    BufferedImage bufferedImage = ImageIO.read(imgFile.getInputStream());
                    int imageWidth = bufferedImage.getWidth();
                    int imageHeight = bufferedImage.getHeight();
                    if (CollectionUtils.isEmpty(checkPic.getCheckPicList())) {
                        //单一尺寸类型校验
                        if (imageHeight != checkPic.getPicHeight().intValue() || imageWidth != checkPic.getPicWidth().intValue()) {
                            //图片限制大小
                            resultMessage.setCode(name);
                            resultMessage.change(false,
                                    "图片尺寸不符合要求！建议尺寸为【" + checkPic.getPicWidth() + "*" + checkPic.getPicHeight() + "】，是否确认上传？");
                            return resultMessage;
                        }
                    } else {
                        Boolean flag = true;
                        StringBuilder stringBuilder = new StringBuilder("");
                        stringBuilder.append(checkPic.getPicWidth()).append("*").append(checkPic.getPicHeight());
                        for (int i = 0; i < checkPic.getCheckPicList().size(); i++) {
                            stringBuilder.append(",").append(checkPic.getCheckPicList().get(i).getPicWidth()).append("*")
                                    .append(checkPic.getCheckPicList().get(i).getPicHeight());
                        }
                        //多尺寸类型校验
                        for (CheckPic pic : checkPic.getCheckPicList()) {
                            if (name.equals(pic.getPicId())) {
                                //匹配上的id
                                flag = false;
                                if (imageHeight != pic.getPicHeight().intValue() || imageWidth != pic.getPicWidth().intValue()) {
                                    //图片限制大小
                                    resultMessage.setCode(name);
                                    resultMessage.change(false, "图片尺寸不符合要求！建议尺寸为【" + stringBuilder.toString() + "】，是否确认上传？");
                                    return resultMessage;
                                }
                            }
                        }
                        //未匹配的id，采用通用尺寸校验
                        if (flag && (imageHeight != checkPic.getPicHeight().intValue()
                                || imageWidth != checkPic.getPicWidth().intValue())) {
                            //图片限制大小
                            resultMessage.setCode(name);
                            resultMessage.change(false, "图片尺寸不符合要求！建议尺寸为【" + stringBuilder.toString() + "】，是否确认上传？");
                            return resultMessage;
                        }
                    }
                }
            }
        } catch (IOException e) {
            resultMessage.change(false, "检查图片报错！");
        }
        return resultMessage;
    }

    @PltLog(log = "导出word数据（通用data）")
    @RequestMapping("/downloadWord")
    @ResponseBody
    public void downloadWord(HttpServletRequest request, HttpServletResponse response, String data) {
        try {
            data = "<html><head><title>菜单管理</title><body>asd</body></html>";
            byte b[] = data.getBytes("utf-8");
            ByteArrayInputStream bais = new ByteArrayInputStream(b);
            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
            //输出文件
            String fileName = "test";
            request.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");//导出word格式
            response.addHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".doc").getBytes(), "utf-8"));
            OutputStream ostream = response.getOutputStream();
            poifs.writeFilesystem(ostream);
            bais.close();
            ostream.close();
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, "CommonServiceController-downloadWord error:{0}", e.getMessage());
        }
    }

}
